import axios, { AxiosResponse } from 'axios';
import env from './config';
import { Message } from '@arco-design/web-vue';
const ssoUrlLogin = env.ssoUrl + '/reLogin?service=';
// import { isWechat } from 'ourwill-feutil/common/ua';

// const ssoUrlLogin = env.ssoUrl + '/login?service=';
// const ssoUrlReset = env.ssoUrl + '/resetPassword?service=';
// const wxauth = () => {
// 	// 参数顺序有要求
// 	const loginURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${env.appid}&redirect_uri=${env.redirect_uri}&response_type=code&scope=${
// 		env.scope
// 	}&state=${location.href}#wechat_redirect`;

// 	console.info('redirect by wxauth', loginURL);
// 	try {
// 		window.location.href = loginURL;
// 	} catch (e) {
// 		console.log(e);
// 	}
// };
export interface CommonResponse extends AxiosResponse {
	ok?: boolean;
}

const config = {
	...env,
	errors(err: any) {
		const msg = err.msg ? err.msg : err.message ? err.message : err.toString();
		Message.error(msg);
		console.error(err);
	},
	login(res: CommonResponse, msg?: string) {
		// const data = res.data;
		// this.errors(data);
		const host = env.local
			? location.origin + `/#/relogin${msg ? '?msg=' + encodeURIComponent(msg) : ''}`
			: location.protocol +
				'//' +
				location.host +
				'/superadmin' +
				`/#/relogin${msg ? '?msg=' + encodeURIComponent(msg) : ''}`;

		// window.location.href = env.host + '/login?service=' + encodeURI(location.origin + location.pathname);
		window.location.href = host;
	},
	filter(res: CommonResponse) {
		const { status, data } = res;
		if (status >= 200 && status < 300) {
			if (data.code === 0) {
				res.ok = true;
				return res;
			} else if (data.msgCode == 401) {
				if (res.headers['set-token']) {
					// 刷新并去掉ticket参数
					location.replace(location.protocol + '//' + location.host + location.pathname);
				} else {
					Message.error(data.msg);
					setTimeout(() => {
						this.login(res);
					}, 1000);
				}
			}
		}
		if (data.code !== 401) {
			this.errors(data.msg);
		} else {
			this.login(res);
		}
		res.ok = false;
		return res;
	},
};

const httpCreate = (baseURL: string, timeout = 120e3) => {
	const instance = axios.create({
		baseURL: config.apiPath + baseURL,
		timeout,
		headers: { 'Cache-Control': 'no-cache', Pragma: 'no-cache' },
	});
	instance.interceptors.response.use(config.filter.bind(config));
	return instance;
};

const getUrlPath = (path: string) => {
	return config.host + path;
};

const { errors, filter, login } = config;

const loginUrl =
	ssoUrlLogin +
	(env.local ? location.origin : (env.nodeEnv === 'production' ? location.origin : config.host) + '/superadmin/#/');

const CancelToken = axios.CancelToken;
const isCancel = axios.isCancel;

export { httpCreate, CancelToken, errors, filter, login, isCancel, getUrlPath, loginUrl };
